package com.examstack.management.controller.action;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.examstack.common.domain.training.TrainingSection;
import com.examstack.common.domain.training.UserTrainingHistory;
import com.examstack.common.util.Page;
import com.examstack.management.service.TrainingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.examstack.common.util.file.FileUploadUtil;
import com.examstack.management.security.UserInfo;

@Controller
public class TrainingAction {

	@Autowired
	private TrainingService trainingService;

	@RequestMapping(value = "/secure/upload-uploadify-file", method = RequestMethod.POST)
	public @ResponseBody String uploadFile(HttpServletRequest request, HttpServletResponse response) {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<String> filePathList = new ArrayList<String>();
		try {
			String function = "training";
			filePathList = FileUploadUtil.uploadFile(request, response, userInfo.getUsername(),function);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		if (filePathList.size() == 0) {
			return "系统错误";
		}

		return filePathList.get(0);
	}

	@RequestMapping(value = "/secure/training/{sectionId}", method = RequestMethod.GET)
	public String trainingPage(Model model, @PathVariable("sectionId") int sectionId) {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<TrainingSection> sectionList = trainingService.getTrainingSectionById(sectionId,-1,null);
		if(sectionList == null){
			model.addAttribute("errorMsg", "章节不存在！");
			return "error";
		}else{
			TrainingSection section=sectionList.get(0);
			String filePath = section.getFilePath();
			section.setFilePath("../" + filePath.replace("\\", "/"));
			if(userInfo.getRolesName().equals("ROLE_ADMIN")){
				model.addAttribute("role", "admin");
			}else{
				model.addAttribute("role", "teacher");
			}
			model.addAttribute("sectionList", sectionList);
			model.addAttribute("sectionId", sectionId);
			model.addAttribute("section", section);
			if(section.getFileType().toLowerCase().equals(".pdf"))
				return "training-pdf";
			else
				return "training";
		}
	}

}
